package com.block.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.block.common.service.IProductCommonService;
import com.block.db.entity.ProductInfo;
import com.block.db.mapper.ProductInfoMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

@Service
public class ProductCommonServiceImpl implements IProductCommonService {

    @Resource
    ProductInfoMapper productInfoMapper;

    /**
     * 根据统计类型和产品ID，获取产品的收益
     * @param productId
     * @return
     */
    @Override
    public BigDecimal getProductProfit(String productId){
        ProductInfo productInfo = this.getProductInfoCache(productId);
        if (ObjectUtil.isEmpty(productInfo)){
            return BigDecimal.ZERO;
        }
        if (ObjectUtil.equal(productInfo.getPriceType(), Integer.valueOf(2))){
            // 如果是注册计价，则不进行统计
            return BigDecimal.ZERO;
        }
        return productInfo.getPriceAmount();
    }


    private  static  final  String PRODUCT_INFO_KEY_PREFIX="PRODUCT:INFO:ID:";
    private  static  final  Long PRODUCT_INFO_KEY_TIME_OUT=4L;

    @Resource
    private RedisTemplate<String, ProductInfo> redisProductInfoTemplate;

    @Override
    public ProductInfo getProductInfoCache(String productId){
        String redisKey = PRODUCT_INFO_KEY_PREFIX+productId;
        ProductInfo productInfo= redisProductInfoTemplate.opsForValue().get(redisKey);
        if(ObjectUtil.isEmpty(productInfo)){
            productInfo = this.productInfoMapper.selectById(productId);
            if(productInfo!=null) {
                redisProductInfoTemplate.opsForValue().set(redisKey, productInfo, PRODUCT_INFO_KEY_TIME_OUT, TimeUnit.HOURS);
            }
        }
        return productInfo;
    }


}
